package com.stars.common.easypoi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.stars.common.valid.MyException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

/**
 * 导入导出工具类
 *
 * @ClassName ExcelUtils
 * @Description:
 * @Author DJ
 * @Date 2019/10/25
 * @Version V1.0
 **/

public class ExcelUtils {

    /**
     * @Description: 注解导出
     * @Param: [list, title, sheetName, pojoClass, fileName, isCreateHeader, response]
     * 数据，标题，sheet1，对象，导出名称，response
     * @return: void
     * @Author: dj
     * @Date: 2019/10/25
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    /**
     * @Description: 导出
     * @Param: [list, title, sheetName, pojoClass, fileName, response]
     * 数据，标题，sheet名称，对象，文件名称，
     * @return: void
     * @Author: dj
     * @Date: 2019/10/25
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        if(null == list && list.isEmpty()){
            throw new MyException("没有要导出的数据");
        }
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    /**
     * 根据模板导出
     * @param dataMap 数据
     * @param fileName 文件名称
     * @param tempUrl 模板地址
     * @param response
     */
    public static  void exportExcelByTemp(Map<Integer, Map<String, Object>> dataMap,String fileName,String [] sheetName,String tempUrl, HttpServletResponse response){
       try{
           Integer [] sheetNum = new Integer[sheetName.length];
           for(int i =0;i<sheetName.length;i++){
               sheetNum[i]=i;
           }
           TemplateExportParams param = new TemplateExportParams(convertTemplatePath(tempUrl), sheetNum);
           param.setSheetName(sheetName);
           Workbook book = ExcelExportUtil.exportExcel(dataMap,param);
           if(null == book){
               throw new MyException("没有找到模板");
           }
           downLoadExcel(fileName,response, book);
       }catch (Exception ex){}

    }


    /**
     * @Description: 导出
     * @Param: [list, fileName, response]
     * @return: void
     * @Author: dj
     * @Date: 2019/10/25
     */
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) ;
        downLoadExcel(fileName, response, workbook);
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new MyException(e.getMessage());
        }
    }

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) ;
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        try {
            List<T> list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
            return list;
        } catch (NoSuchElementException e) {
            throw new MyException("模板不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(e.getMessage());
        }
    }

    /**
     * @Description: 导入
     * @Param: [file, titleRows, headerRows, pojoClass]
     * @return: java.util.List<T>
     * @Author: dj
     * @Date: 2019/10/25
     */
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        try {
            List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
            return list;
        } catch (NoSuchElementException e) {
            throw new MyException("excel文件不能为空");
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }

    }
    private static String convertTemplatePath(String path) {
        // 如果是windows 则直接返回
        // if (System.getProperties().getProperty("os.name").contains("Windows")) {
        // return path;
        // }

        Resource resource = new ClassPathResource(path);
        FileOutputStream fileOutputStream = null;
        // 将模版文件写入到 tomcat临时目录
        String folder = System.getProperty("catalina.home");
        File tempFile = new File(folder + File.separator + path);
        // System.out.println("文件路径：" + tempFile.getPath());
        // 文件存在时 不再写入
        if (tempFile.exists()) {
            return tempFile.getPath();
        }
        File parentFile = tempFile.getParentFile();
        // 判断父文件夹是否存在
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(resource.getInputStream());
            fileOutputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[10240];
            int len = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return tempFile.getPath();
    }
}
